package com.chixing.ih.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @author 刘岩
 * @version 1.0
 * @Desc Practice makes perfect
 * @date 2020/9/10 14:17
 */
@Component
@Configuration
public class SendNoteUtil {
    //LTAI4GHTGzn8AcAu4KBReemn
    //MwcbUcGaHrNXr33qDVeND8j3f5M0oT

    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${spring.redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;


    //验证平台信息 开发者无需任何更改
    private static final String dysmsapi = "dysmsapi.aliyuncs.com";

    DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4GHTGzn8AcAu4KBReemn", "MwcbUcGaHrNXr33qDVeND8j3f5M0oT");
    IAcsClient client = new DefaultAcsClient(profile);

    //这一步的两个参数,一个是要发送验证码的手机号 一个是模板Code用来区分模板作用的
    public String sendNoteMessgae(String PhoneNumbers, String template) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        if(sb.charAt(0)=='0'){
            sb.setCharAt(0,'1');
        }
        CommonRequest request = new CommonRequest();
        //request.setSysProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(dysmsapi);
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);//接受验证码的手机号
        request.putQueryParameter("SignName", "IT帮");//签名
        //模板代码,我暂时用的参数,你可以直接写成模板码,模板码参考第八步
        request.putQueryParameter("TemplateCode", template);
        //用户定义的验证码内容
        request.putQueryParameter("TemplateParam", "{code:" + sb.toString() + "}");
        redisUtil.set(REDIS_KEY_PREFIX_AUTH_CODE + PhoneNumbers, sb.toString(), AUTH_CODE_EXPIRE_SECONDS);
        try {
            CommonResponse response = client.getCommonResponse(request);
            String returnStr = response.getData();
            JSONObject jsonObject = JSONObject.parseObject(returnStr);
            //返回的信息
            return jsonObject.getString("Message");
        } catch (ServerException e) {
            return e.getErrMsg();
        } catch (ClientException e) {
            return e.getErrMsg();
        }
    }



}